﻿namespace Pibby.Core.IO
{
	public class FileSearcher
	{
		public FileSearcher()
		{
			this.SearchPaths = new IFolderCollection();
		}

		public string FileName
		{
			get;
			set;
		}

		public IFolderCollection SearchPaths
		{
			get;
			private set;
		}

		public static IFile Find(string fileName, IFolder searchPath)
		{
			var strategy = new FileSearcher();

			strategy.FileName = fileName;
			strategy.SearchPaths.Add(searchPath);

			return strategy.Find();
		}

		public static IFile Find(string fileName, IFolderCollection searchPaths)
		{
			var strategy = new FileSearcher();

			strategy.FileName = fileName;

			foreach (var path in searchPaths)
			{
				strategy.SearchPaths.Add(path);
			}

			return strategy.Find();
		}

		public IFile Find()
		{
			Contract.EnsureIsNotNullOrEmpty(this.FileName, "Filename is not set");
			Contract.EnsureThat(this.SearchPaths.Count > 0, "No paths to search");

			//// use file discoverer on each folder ...

			IFile foundFile = null;

			string searchMask = "*" + System.IO.Path.GetExtension(this.FileName);

			foreach (IFolder folder in this.SearchPaths)
			{
				IFileCollection matches = folder.GetFiles(searchMask);

				foreach (IFile match in matches)
				{
					if (match.Name == this.FileName)
					{
						foundFile = match;
						break;
					}
				}

				if (foundFile != null)
				{
					break;
				}
			}

			if (foundFile == null)
			{
				throw new System.IO.FileNotFoundException(
															string.Format(System.Globalization.CultureInfo.CurrentUICulture,
															"Cannot find \'{0}\' in paths supplied.", 
															this.FileName));
			}

			return foundFile;
		}
	}
}
